package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.config.PasswordConfig;
import com.leyou.auth.entity.ApplicationInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import com.netflix.discovery.converters.Auto;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ApplicationInfoMapper infoMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 用户登录
     * @param username
     * @param password
     */
    public void login(String username, String password, HttpServletResponse response) {
        try {
            // 校验用户名和密码
            UserDTO ud = userClient.queryUserByUsernameAndPassword(username, password);
            // 生成jwt
            UserInfo userInfo = new UserInfo(ud.getId(),ud.getUsername(), "guest");
            String token = JwtUtils.generateTokenExpireInMinutes(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getUser().getExpire());
            // 存入cookie
            CookieUtils.newCookieBuilder()  // 我们把token写入浏览器的cookie中
                    .name(jwtProperties.getUser().getCookieName()) // cookie的名称
                    .value(token) // 生成的token
                    .domain(jwtProperties.getUser().getCookieDomain()) // cookie对应的域名
                    .httpOnly(true) // 避免XSS攻击
                    .response(response) // 响应对象，把cookie写入浏览器
                    .build(); // 完成cookie的写入浏览器
        } catch (Exception e) {
            log.error("【授权中心】用户登录失败：{}",e.getMessage());
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
    }

    /**
     * 校验用户
     * @param request
     * @return
     */
    public UserInfo verifyUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 从cookie中获取token
            String token = CookieUtils.getCookieValue(request, jwtProperties.getUser().getCookieName());
            // 解析token
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), UserInfo.class);
            //==========================================================================================================
            //==================================     黑名单校验                         ================================
            //==========================================================================================================
            String key = payload.getId();
            Boolean bool = redisTemplate.hasKey(key);
            if(bool != null && bool){
                // 黑名单中存在，抛异常
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            //==========================================================================================================
            // 取出token的失效的时间：如果失效时间与当前时间相比，如果小于10分钟，重新生成一个新的token
            Date expiration = payload.getExpiration();
            // 减去10分钟
            DateTime dateTime = new DateTime(expiration).minusMinutes(jwtProperties.getUser().getRefreshTime());
            if(dateTime.isBeforeNow()){
                // 小于10分钟
                String newToken = JwtUtils.generateTokenExpireInMinutes(payload.getUserInfo(), jwtProperties.getPrivateKey(), jwtProperties.getUser().getExpire());
                // 写入浏览器
                // 存入cookie
                CookieUtils.newCookieBuilder()  // 我们把token写入浏览器的cookie中
                        .name(jwtProperties.getUser().getCookieName()) // cookie的名称
                        .value(newToken) // 生成的新的token
                        .domain(jwtProperties.getUser().getCookieDomain()) // cookie对应的域名
                        .httpOnly(true) // 避免XSS攻击
                        .response(response) // 响应对象，把cookie写入浏览器
                        .build(); // 完成cookie的写入浏览器
            }
            // 返回用户信息
            return payload.getUserInfo();
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }

    /**
     * 用户退出
     * @param request
     * @param response
     */
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 获取请求中的token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getUser().getCookieName());
        // 解析token
        Payload<Object> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
        } catch (Exception e) {
            // 如果解析token失败，说明token已经过期，无需存入redis中
            return;
        }
        // 获取token的剩余的时间
        long expTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        // 存入redis中： 有效期如果是大于3秒，才存入redis
        if(expTime > 3000){
            String key = payload.getId();
            redisTemplate.opsForValue().set(key, "1", expTime, TimeUnit.MILLISECONDS);
        }
        // 删除浏览器的cookie
        CookieUtils.deleteCookie(
                jwtProperties.getUser().getCookieName(),
                jwtProperties.getUser().getCookieDomain(),
                response
                );
    }

    /**
     * 微服务授权
     * @param id
     * @param secret
     * @return
     */
    public String authorization(Long id, String secret) {
        // 1、校验微服务的id和密码
        ApplicationInfo app = infoMapper.selectByPrimaryKey(id);
        // 1.1 校验是否存在微服务
        if(app == null){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        // 1.2 校验密码
        if(!passwordEncoder.matches(secret, app.getSecret() )){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }

        // 2、校验当前微服务具有哪些权限
        List<Long> targetIdList = infoMapper.queryTargetIdList(id);

        // 3、把对象封装到token的载荷对象中
        AppInfo appInfo = new AppInfo();
        appInfo.setId(id);
        appInfo.setServiceName(app.getServiceName());
        appInfo.setTargetList(targetIdList);

        // 4、生成token； 有效期：25小时  * 60 = 1500分钟
        String token = JwtUtils.generateTokenExpireInMinutes(appInfo, jwtProperties.getPrivateKey(), jwtProperties.getApp().getExpire());

        // 5、返回
        return token;
    }
}
